<template>
  <AdminLayout>
    <!-- 用户管理主容器 -->
    <div>
      <h1>用户管理</h1>
      <!-- 注册新用户表单 -->
      <el-form :model="form" ref="formRef" label-width="80px" style="margin-bottom: 20px; max-width: 400px;">
        <el-form-item label="用户名">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onRegister">注册</el-button>
          <el-button type="success" @click="onLogin">登录</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-alert v-if="msg" :title="msg" type="info" show-icon style="margin-bottom: 20px;" />
      <!-- 用户列表 -->
      <el-table :data="users" style="width: 100%">
        <el-table-column prop="username" label="用户名" width="200" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" type="danger" @click="onDelete(scope.row._id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </AdminLayout>
</template>

<script setup>
import AdminLayout from '~/components/AdminLayout.vue'
import { ref, onMounted } from 'vue'
const users = ref([])
const form = ref({ username: '', password: '' })
const formRef = ref(null)
const msg = ref('')

// 获取用户列表
async function fetchUsers() {
  const res = await fetch('/api/users')
  users.value = await res.json()
}

// 注册
async function onRegister() {
  const res = await fetch('/api/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ ...form.value, action: 'register' })
  })
  const data = await res.json()
  msg.value = data.message || (data.success ? '注册成功' : '注册失败')
  if (data.success) {
    await fetchUsers()
    onReset()
  }
}

// 登录
async function onLogin() {
  const res = await fetch('/api/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ ...form.value, action: 'login' })
  })
  const data = await res.json()
  msg.value = data.message || (data.success ? '登录成功' : '登录失败')
  if (data.success) {
    onReset()
  }
}

// 删除用户
async function onDelete(id) {
  await fetch(`/api/users?id=${id}`, { method: 'DELETE' })
  await fetchUsers()
}

// 重置表单
function onReset() {
  form.value = { username: '', password: '' }
  if (formRef.value) formRef.value.clearValidate && formRef.value.clearValidate()
}

onMounted(fetchUsers)
</script>

<style scoped>
h1 {
  margin-bottom: 30px;
}
</style> 